<!-- 商品详情页评论内容 -->
<template>
  <u-popup
    v-model="show"
    mode="bottom"
    border-radius="24"
    safe-area-inset-bottom
    @close="closeSkuBox"
  >
    <view class="popup-body" v-if="goodsInfo">
      <view class="pup-details">
        <view class="pup-details-top">
          <view class="goods-img">
            <image
              :src="attrData ? attrData.pic : goodsData.cover_pic"
              mode="aspectFill"
            ></image>
          </view>
          <view class="goods-info">
            <view class="price">
              <text>¥</text>
              <text>{{
                (attrData ? attrData.price : goodsData.price) | priceBeforeZero
              }}</text>
              <text>{{
                (attrData ? attrData.price : goodsData.price) | priceAfterZero
              }}</text>
            </view>
            <view class="rest-num">
              {{ $t("goods.inventory")
              }}{{ attrData ? attrData.num : goodsData.num }}</view
            >
            <view class="has-selected" v-if="skuText"
              >{{ $t("goods.choosedSku") }} {{ skuText }}</view
            >
          </view>
        </view>
        <view class="attr-section">
          <view class="sku-attr">
            <view
              class="attr-group"
              v-for="(item, index) in goodsData.attr_group_list"
              :key="index"
            >
              <view class="attr-group-name">{{ item.attr_group_name }}</view>
              <view class="attr-list">
                <view
                  v-for="(SecondItem, SecondIndex) in item.attr_list"
                  :key="SecondIndex"
                  class="attr-item"
                  :class="[SecondItem.isSelect ? 'selected' : '']"
                  @click="selectSkuItem(item, SecondItem)"
                >
                  {{ SecondItem.attr_name }}
                </view>
              </view>
            </view>
          </view>

          <view class="shop-num">
            <view class="shop-num-text">{{ $t("goods.number") }}</view>
            <view>
              <!-- 计数器 -->
              <numberStep v-model="num" :min="1"></numberStep>
            </view>
          </view>
        </view>
      </view>

      <!-- 关闭弹框 -->
      <view class="close-icon" @click="show = false">
        <view class="icon-box">
          <i class="iconfont icon-close"></i>
        </view>
      </view>
      <!-- 底部按钮 -->
      <view class="foot-btns">
        <view class="foot-content">
          <view class="confirm-btn" @click="confirmSku">{{
            $t("list.confirm")
          }}</view>
        </view>
      </view>
    </view>
  </u-popup>
</template>

<script>
import goodApi from "@/api/goods.js";
import numberStep from "@/components/cyyUi/numberStep/index.vue";

export default {
  data() {
    return {
      show: false,
      num: 1,
      goodsData: "",
      selectSku: [],
      attrData: "",
      skuText: "",
    };
  },
  components: {
    numberStep,
  },
  props: {
    // 商品id
    skuData: {
      type: Object,
      default: () => {
        return {
          goodsId: 0,
          cartId: 0,
        };
      },
    },
    goodsInfo: {
      type: Object,
      default: null,
    },
  },
  mounted() {},
  filters: {
    priceBeforeZero(val) {
      if (!val) return "";
      val = val.toString();
      if (val.indexOf(".") < 0) return `${val}.`;
      return val.substr(0, val.indexOf("."));
    },
    priceAfterZero(val) {
      if (!val) return "";
      val = val.toString();
      if (val.indexOf(".") < 0) return "00";
      return val.substr(val.indexOf("."), val.length);
    },
  },
  computed: {
    // 计算已选规格名称
    selectSkuName() {
      if (this.selectSku.length) {
        let name = "";
        this.selectSku.forEach((item) => {
          name += `${item.attr_list[0].attr_name} `;
        });
        return name;
      } else {
        return "";
      }
    },
    // 计算是否选中
    isSelectSkuItem() {
      return (skuId) => {
        try {
          this.selectSku.forEach((item) => {
            if (skuId === item.attr_group_id) {
              throw item.attr_list[0].attr_id;
            }
          });
          return "";
        } catch (id) {
          return id;
        }
      };
    },
    // 计算库存
    inStock() {
      if (this.selectSku.length != this.goodsData.attr_group_list?.length) {
        return this.goodsData.num;
      } else {
        return this.attrData.num;
      }
    },
  },
  methods: {
    // 选中规格
    async clickSkuItem(sku, skuItem) {
      // 数据储存方法
      let selectData = {
        ...sku,
        attr_list: [skuItem],
      };
      if (!this.selectSku.length) {
        this.selectSku.push(selectData);
      } else {
        let index = this.selectSku.findIndex((item) => {
          return item.attr_group_id === sku.attr_group_id;
        });
        if (index == -1) {
          this.selectSku.push(selectData);
        } else {
          this.selectSku.splice(index, 1, selectData);
        }
      }
      // 选完所有规格查询规格库存
      if (this.selectSku.length == this.goodsData.attr_group_list.length) {
        var form = {};

        form.attr_list = JSON.stringify(
          this.selectSku.map((item) => {
            return item.attr_list[0].attr_id;
          })
        );
        form.goods_id = this.skuData.goodsId;
        form.number = this.num;
        try {
          const res = await this.$allrequest.goods.goodsAttrInfo(form);
          if (res.code != 0) throw res;
          this.attrData = res.data;
        } catch (res) {
          uni.showToast({
            title: res.msg || this.$t("user.err"),
            icon: "none",
          });
        }
      }
    },
    // 显示弹框
    showPopup() {
      this.$nextTick(async () => {
        // 获取商品详情
        this.attrData = this.$options.data().attrData;
        this.show = !this.show;
        this.num = this.goodsInfo.num;
        this.goodsInfo.attr_list.forEach((d) => {
          this.skuText = this.skuText + d.attr_name + ";";
        });
        this.getGoodData();
      });
    },
    // 获取商品详情
    async getGoodData() {
      try {
        const res = await goodApi.goodsDetails(
          { id: this.skuData.goodsId },
          true
        );
        if (res.code != 0) throw false;
        res.data.attr = JSON.parse(res.data.attr);
        // 处理默认值选中
        res.data.attr_group_list.forEach((d, index) => {
          d.attr_list.forEach((k, i) => {
            k["isSelect"] = false;
            this.goodsInfo.attr_list.forEach((p) => {
              if (
                p.attr_group_name == d.attr_group_name &&
                p.attr_name == k.attr_name
              ) {
                k["isSelect"] = true;
              }
            });
          });
        });
        this.goodsData = res.data;

        if (this.goodsInfo) {
          let { goods_pic, price, max_num } = this.goodsInfo;
          this.goodsData.goods_pic = goods_pic
          this.goodsData.price = price
          this.goodsData.num = max_num
        }
      } catch (error) {
        uni.showToast({
          title: this.$t("alipay.goodsFail"),
          duration: 2000,
          icon: "none",
        });
      }
    },
    // 关闭弹框
    closeSkuBox() {
      this.selectSku = this.$options.data().selectSku;
      this.num = this.$options.data().num;
      this.skuText = "";
      this.$emit("close");
    },
    // 选择属性
    async selectSkuItem(item, child) {
      // 处理默认值选中
      this.goodsData.attr_group_list.forEach((d) => {
        if (d.attr_group_id == item.attr_group_id) {
          d.attr_list.forEach((k) => {
            k["isSelect"] = false;
            if (k.attr_id == child.attr_id) {
              k["isSelect"] = true;
            }
          });
        }
      });
      let flagNum = 0;
      this.goodsData.attr_group_list.forEach((d) => {
        let flag = d.attr_list.some((k) => {
          return k.isSelect;
        });
        if (flag) flagNum++;
      });
      // 选完后获取sku组合属性
      if (flagNum == this.goodsData.attr_group_list.length) {
        var form = {
          attr_list: [],
        };
        this.goodsData.attr_group_list.forEach((d) => {
          d.attr_list.forEach((k) => {
            if (k.isSelect) form.attr_list.push(k.attr_id);
          });
        });
        form.goods_id = this.skuData.goodsId;
        form.number = this.num;
        try {
          const res = await this.$allrequest.goods.goodsAttrInfo(form);
          if (res.code != 0) throw res;
          this.attrData = res.data;
        } catch (res) {
          uni.showToast({
            title: res.msg || this.$t("user.err"),
            icon: "none",
          });
        }
      }
    },
    // 点击确认选择sku
    async confirmSku() {
      let flagNum = 0;
      this.goodsData.attr_group_list.forEach((d) => {
        let flag = d.attr_list.some((k) => {
          return k.isSelect;
        });
        if (flag) flagNum++;
      });
      // 选完后获取sku组合属性
      if (flagNum != this.goodsData.attr_group_list.length) {
        return uni.showToast({ title: this.$t("diy.sku"), icon: "none" });
      }
      let form = {
        attr: [],
        num: this.num,
        cart_id: this.skuData.cartId,
      };
      this.goodsData.attr_group_list.forEach((d) => {
        d.attr_list.forEach((k) => {
          if (k.isSelect) {
            form.attr.push({
              attr_group_id: d.attr_group_id,
              attr_id: k.attr_id,
            });
          }
        });
      });
      form.attr = JSON.stringify(form.attr);
      // 请求后台修改数据
      try {
        const res = await goodApi.updateGoodsSku(form);
        if (res.code != 0) throw res;
        this.$utils.toast(this.$t("common.saveSuc"));
        this.show = false;
        this.$emit("confirm");
      } catch (res) {
        uni.showToast({
          title: res.mcg || this.$t("user.err"),
          icon: "none",
        });
      }
    },
  },
  watch: {},
};
</script>

<style lang="scss" scoped>
.popup-body {
  width: 100%;
  background-color: #ffffff;
  padding-top: 4.8vw;
  max-height: 80vh;
  position: relative;

  .pup-details {
    padding-bottom: 20rpx;
    width: 100%;
    .pup-details-top {
      padding: 0 4.8vw;
      display: flex;
      align-items: flex-end;
      position: relative;
      .goods-img {
        width: 25.6vw;
        height: 25.6vw;
        background: #f2f2f2;
        border-radius: 1.86vw;
        overflow: hidden;
        margin-right: 2.67vw;
        flex-shrink: 0;
        image {
          width: 100%;
          height: 100%;
          display: block;
        }
      }
      .goods-info {
        text-align: left;
        .price {
          display: flex;
          align-items: flex-end;
          font-size: 30rpx;
          font-family: PingFang SC;
          font-weight: 600;
          color: #f0250e;
          text:nth-child(2) {
            font-size: 44rpx;
            line-height: 47rpx;
          }
        }
        .rest-num {
          font-size: 22rpx;
          font-family: PingFang SC;
          font-weight: 400;
          color: #f0250e;
        }
        .has-selected {
          font-size: 22rpx;
          font-family: PingFang SC;
          font-weight: 400;
          color: #8c8c8c;
        }
      }
    }

    .attr-section {
      width: 100%;
      margin-top: 20rpx;
      max-height: 57vh;
      overflow-y: scroll;
      overflow-x: hidden;
      .sku-attr {
        padding-bottom: 20rpx;
      }
      .attr-group {
        padding: 3.2vw 3.2vw 0 3.2vw;
        width: 100%;
        margin-bottom: 2.67vw;
        .attr-group-name {
          margin-bottom: 2.4vw;
          padding-left: 1.6vw;
          font-size: 26rpx;
          font-family: PingFang SC;
          font-weight: 600;
          color: #262626;
        }
        .attr-list {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          .attr-item {
            margin: 1.6vw;
            background: #f2f1f2;
            border-radius: 3.6vw;
            height: 7.2vw;
            padding: 0 2.67vw;
            line-height: 7.2vw;
            text-align: center;
            flex-shrink: 0;
            font-size: 26rpx;
            font-family: PingFang SC;
            font-weight: 400;
            color: #262626;
          }
          .noneActive {
            color: #8c8c8c;
            text-decoration: line-through;
          }
          .selected {
            background: #fbeceb;
            color: #f0250e;
          }
        }
      }
    }

    .shop-num {
      padding: 0 4.8vw;
      height: 10.66vw;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .shop-num-text {
        font-size: 26rpx;
        font-family: PingFang SC;
        font-weight: 600;
        color: #262626;
      }
    }
  }

  .close-icon {
    width: 12.78vw;
    height: 12.78vw;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 11;
    display: flex;
    justify-content: center;
    align-items: center;

    .iconfont {
      color: #262626;
      font-weight: 600;
      font-size: 36rpx;
    }
  }

  .foot-btns {
    width: 100%;
    border-top: 1px solid #f0f1f3;
    .foot-content {
      width: 100%;
      height: 13.34vw;
      display: flex;
      justify-content: center;
      align-items: center;
      .confirm-btn {
        width: 90.4vw;
        height: 10.134vw;
        border-radius: 5.067vw;
        background: linear-gradient(90deg, #f22407 0%, #f84d17 100%);
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 26rpx;
        font-family: PingFang SC;
        font-weight: 600;
        color: #ffffff;
      }
    }
  }
}

.sku-popup-box {
  height: calc(100vh - 400rpx);
}
.skuHead {
  position: relative;
  padding: 36rpx;
  display: flex;
  .goodsPic {
    width: 200rpx;
    min-width: 200rpx;
    height: 200rpx;
    background-color: #999;
    border-radius: 14rpx;
    overflow: hidden;
    image {
      width: 100%;
      height: 100%;
    }
  }
  .goodsInfo {
    height: 200rpx;
    margin-left: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    .goodPrice {
      display: flex;
      align-items: baseline;
      font-size: 36rpx;
      color: #f7271f;
      font-weight: 500;
      text:nth-child(2) {
        font-size: 48rpx;
      }
    }
    .count {
      font-size: 22rpx;
      color: #8c8c8c;
    }
    .choosedSku {
      margin-top: 10rpx;
      font-size: 22rpx;
      color: #262626;
    }
  }
}
.skuBox {
  position: relative;
  flex: 1;
  height: 0;
  .skuList {
    display: flex;
    flex-direction: column;
    .skuItem {
      padding: 15rpx 36rpx;
      margin-bottom: 10rpx;
      .skuTitle {
        font-size: 26rpx;
        display: block;
        color: #262626;
        margin-bottom: 20rpx;
      }
      .skus {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        text {
          padding: 10rpx 24rpx;
          border-radius: 99px;
          font-size: 26rpx;
          color: #262626;
          background-color: #f2f2f2;
          margin: 10rpx 24rpx 10rpx 0;
        }
        .choosed {
          color: #f7271f;
          background-color: #fcedeb;
        }
      }
    }
  }
}
.goodsNum {
  margin-top: 10rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12rpx 36rpx;
  font-size: 26rpx;
  color: #262626;
  font-weight: 500;
}
.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12rpx 36rpx;
  border-top: 1px solid #f2f2f2;
  margin-top: 20rpx;
  text {
    width: 678rpx;
    text-align: center;
    height: 76rpx;
    line-height: 76rpx;
    font-size: 26rpx;
    font-weight: 500;
    color: #fff;
    background: linear-gradient(90deg, #f22407 0%, #f84d17 100%);
    border-radius: 38rpx;
  }
}
.detailBtn {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12rpx 36rpx;
  border-top: 1px solid #f2f2f2;
  margin-top: 20rpx;
  text {
    width: 328rpx;
    height: 76rpx;
    line-height: 76rpx;
    text-align: center;
    border-radius: 38rpx;
    font-size: 26rpx;
    color: #fff;
    font-weight: 500;
  }
  text:nth-child(1) {
    background: linear-gradient(90deg, #ffa700, #ffbb00);
  }
  text:nth-child(2) {
    background: linear-gradient(90deg, #f22300, #ff4c17);
  }
}
</style>
